package com.cctv.order.message;

import com.cctv.order.utils.JsonUtil;
import com.cctv.product.common.ProductInfoOutput;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: cctv
 * @Date: 2019/6/11 15:37
 */
@Component
@Slf4j
@Transactional
public class ProductInfoReceiver {
    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message) {
        List<ProductInfoOutput> productInfoOutputList = JsonUtil.fromJson(message, new TypeToken<List<ProductInfoOutput>>() {
        }.getType());
        log.info("从队列{}接收到消息：{}", "productInfo", productInfoOutputList);
        // 储存到redis
        for (ProductInfoOutput productInfoOutput : productInfoOutputList) {
            stringRedisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE, productInfoOutput.getProductId()),
                    String.valueOf((productInfoOutput.getProductStock())));

        }
    }
}
